import { defineStore } from 'pinia'
import { loginApi, logoutApi, getUserInfo } from '@/api/auth'
import router from '@/router'
import axios from 'axios'

export const useAuthStore = defineStore('auth', {
  state: () => ({
    userId: null,
    userType: null,
    token: null,
    userInfo: null,
    loading: false
  }),

  actions: {
    async login(credentials) {
      this.loading = true
      try {
        console.log('正在尝试登录，提交数据:', credentials)
        
        // 1. 调用登录API
        const response = await loginApi(credentials)
        console.log('登录API响应:', response)
        
        if (!response.data) {
          throw new Error('登录失败：响应数据为空')
        }

         // 获取用户ID - 现在直接从response.data.userId获取
    const userId = response.data.userId
    if (!userId) {
      console.error('响应数据:', response.data)
      throw new Error('登录失败：响应中缺少userId字段')
    }
        // 3. 更新store状态
        this.token = response.data.token
        this.userId = userId
        this.userType = credentials.userType

        // 4. 设置axios全局请求头
        if (this.token) {
          axios.defaults.headers.common['Authorization'] = `Bearer ${this.token}`
          console.log('已设置Authorization头')
        }

        // 5. 获取用户详细信息
        try {
          const userInfoResponse = await getUserInfo()
          this.userInfo = userInfoResponse.data
          console.log('用户详细信息:', this.userInfo)
        } catch (error) {
          console.warn('获取用户信息失败，使用基础信息:', error)
          this.userInfo = {
            id: userId,
            username: credentials.username,
            userType: credentials.userType
          }
        }

        // 6. 持久化存储
        localStorage.setItem('token', this.token)
        localStorage.setItem('userId', this.userId)
        localStorage.setItem('userType', this.userType)
        localStorage.setItem('userInfo', JSON.stringify(this.userInfo))

        // 7. 返回必要数据
        return {
          success: true,
          userId: this.userId,
          userType: this.userType
        }

      } catch (error) {
        console.error('登录过程中出错:', error)
        this.resetAuth()
        
        // 改进错误处理
        let errorMessage = '登录失败'
        if (error.response) {
          if (error.response.status === 404) {
            errorMessage = '登录接口不存在，请检查API路径'
          } else if (error.response.status === 401) {
            errorMessage = '用户名或密码错误'
          }
        }
        
        throw new Error(errorMessage)
      } finally {
        this.loading = false
      }
    },

    async logout() {
  this.loading = true
  try {
    console.log('正在执行登出操作')
    
    // 直接使用axios调用后端接口
    await axios.post('/api/auth/logout', null, {
      headers: {
        'Authorization': `Bearer ${this.token}`
      }
    })
    
    this.resetAuth()
    await router.push('/')
    console.log('登出成功')
  } catch (error) {
    console.error('登出失败:', error)
    throw error
  } finally {
    this.loading = false
  }
},

    resetAuth() {
      console.log('正在重置认证状态')
      // 清除状态
      this.token = null
      this.userId = null
      this.userType = null
      this.userInfo = null
      
      // 清除本地存储
      localStorage.removeItem('token')
      localStorage.removeItem('userId')
      localStorage.removeItem('userType')
      localStorage.removeItem('userInfo')
      
      // 移除axios请求头
      delete axios.defaults.headers.common['Authorization']
      console.log('认证状态已重置')
    },

    async fetchUserInfo() {
      this.loading = true
      try {
        console.log('正在获取用户信息')
        const response = await getUserInfo()
        this.userInfo = response.data
        localStorage.setItem('userInfo', JSON.stringify(response.data))
        console.log('用户信息获取成功:', this.userInfo)
        return response.data
      } catch (error) {
        console.error('获取用户信息失败:', error)
        throw error
      } finally {
        this.loading = false
      }
    },

    initializeAuth() {
      console.log('正在初始化认证状态')
      const token = localStorage.getItem('token')
      const userId = localStorage.getItem('userId')
      const userType = localStorage.getItem('userType')
      const userInfo = JSON.parse(localStorage.getItem('userInfo'))
      
      if (token && userId && userType) {
        this.token = token
        this.userId = userId
        this.userType = userType
        this.userInfo = userInfo
        axios.defaults.headers.common['Authorization'] = `Bearer ${token}`
        console.log('认证状态初始化完成')
      } else {
        console.log('没有找到有效的认证信息')
      }
    },

    isAuthenticated() {
      const authenticated = !!this.token && !!this.userId
      console.log('检查认证状态:', authenticated)
      return authenticated
    }
  }
})

// auth.js 或 stores/auth.js
export const logout = () => {
  // 清除所有认证相关状态
  localStorage.removeItem('token')
  localStorage.removeItem('userInfo')
  
  // 重置认证状态
  isAuthenticated.value = false
  currentUser.value = null
  
  console.log('已成功退出登录状态')
  
  // 强制刷新页面清除所有状态
  window.location.href = '/login' // 或您的登录页路径
}